package org.hepeng.fabric.gateway.pool;

import org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.hepeng.fabric.gateway.pool.channel.GRpcChannelProperties;
import org.hepeng.fabric.gateway.pool.channel.GRpcChannels;
import org.hyperledger.fabric.client.Gateway;
import org.hyperledger.fabric.client.Network;
import org.hyperledger.fabric.client.identity.Identities;
import org.hyperledger.fabric.client.identity.Signers;
import org.hyperledger.fabric.client.identity.X509Identity;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author he peng
 * @date 2022/3/24
 */
public class FabricGatewayObjectFactory extends BaseKeyedPooledObjectFactory<GatewayKey, FabricGatewayObject> {


    private final GRpcChannelProperties properties;

    public FabricGatewayObjectFactory(GRpcChannelProperties properties) {
        this.properties = properties;
    }

    @Override
    public FabricGatewayObject create(GatewayKey key) throws Exception {
        assert Objects.nonNull(key);

        Gateway gateway = Gateway.newInstance()
                .identity(new X509Identity(key.getMspId() , Identities.readX509Certificate(key.getX509CertificatePem())))
                .signer(Signers.newPrivateKeySigner(Identities.readPrivateKey(key.getPrivateKeyPem())))
                .connection(GRpcChannels.getChannel(properties))
                .connect();

        Network network = gateway.getNetwork(key.getChannel());
        Map<String , Network> networkMap = new HashMap<>();
        networkMap.put(key.getChannel() , network);

        return new FabricGatewayObject()
                .setKey(key)
                .setGateway(gateway).setNetworks(networkMap);
    }


    @Override
    public PooledObject<FabricGatewayObject> wrap(FabricGatewayObject value) {
        return new FabricGatewayPooledObject(value);
    }

    @Override
    public void destroyObject(GatewayKey key, PooledObject<FabricGatewayObject> p) throws Exception {
        p = null;
    }
}
